package coupon

import (
	"OnlineRetailers/controllers/admin/PageNum"
	session2 "OnlineRetailers/controllers/admin/session"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models"
	"OnlineRetailers/models/Admin"
	"OnlineRetailers/models/Admin/resMes"
	error2 "OnlineRetailers/models/errorDeal"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strconv"
)

type GetCoupon struct {
	beego.Controller
}

func (c *GetCoupon) GetCoupon() {
	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()
	var addr = "/Coupon/GetCoupon"
	res := resMes.GetCoupon{}
	coupons := []*Admin.Coupon{}
	log := &error2.Log{}

	var err error
	o := orm.NewOrm()
	Page, err := c.GetInt("Page", 0)
	begin, err := c.GetInt("begin", 0)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	limit := ""
	if begin == 0 {
		err = session2.CheckSession(c.Ctx.Request.Header["Session"], 0)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
		limit = " limit " + strconv.Itoa(models.AdminPage) + " offset " + strconv.Itoa(models.AdminPage*Page)
		count, err := PageNum.GetPageNum("coupon", o)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, "GetPageNum"+err.Error())
			return
		}
		res.Count = count / models.AdminPage
	}

	sql := "select * from `coupon`  order by `coupon_id` desc" + limit
	_, err = o.Raw(sql).QueryRows(&coupons)

	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	sql = "select * from `coupon_classifications` left join `classification` on classification.classification_id=coupon_classifications.classification_id where coupon_classifications.coupon_id=?"
	for i := 0; i < len(coupons); i++ {

		_, err = o.Raw(sql, coupons[i].CouponId).QueryRows(&coupons[i].Classification)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	}

	res.Coupon = coupons
	res.Code = "200"
	c.Data["json"] = res

}
